package pool.tablename;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;

import logger.ProcessLogger;

//import basicprocess.Basicprocess;
//import logger.ProcessLogger;
import database.RecordSearch;
import dbmanager.ChekInMaster;
import dbmanager.Column;
import dbmanager.DBManager;
import dbmanager.GetIdName;
//import errorvalidation.Preprocess;

import utility.ConvertToLower;

import utility.MessageGenerator;
/**
 * 
 * @author Administrator
 * Transaction class do the insertion of the transaction which is done 
 * between seller and buyer in transaction table and inserts the item in 
 * the transaction_details table.Without item transaction is not possible.
 * All properties of Transaction and Items are optional.
 * Transaction class do the Updation,Deletion and view operation for the 
 * transaction which is already done.
 * Transaction contains the following fields
 * id  stores id of transaction made.
 * BUYER as a name of buyer
 * SELLER as a name of seller
 * order_date stores order date on which transaction was made.
 * delivery_date stores date of delivery for the given transaction.
 * string transaction_type stores type of transaction made , such as purchase order, dispatch order, etc.
 * amount,vat,sales_tax,service_tax,octroi,total_amount,
 *	
 */
 

public class Transaction  extends SubPool
{
	private String masterTable = "transaction";
	private String pl_tableName = "trans_property_details";
	
	private Hashtable<Object,Object> TransactionMap = new Hashtable<Object, Object>() ;
	
	public Trans_property_details tpd ;	
	public Transaction_details td ;	
	
	private Hashtable<Object,Object> newTransactionMap = new Hashtable<Object,Object>(); /** It will get stores new mesage for Update.*/
	private Hashtable<Object,Object> oldTransactionMap = new Hashtable<Object, Object>();
	String GETPROPERTY="getproperty";
	private Hashtable<Object,Object> ViewHashtable = new Hashtable<Object, Object>();
	private Hashtable<Object,Object> PropertyViewHashtable = new Hashtable<Object, Object>();
	private Hashtable<Object,Object> TransDetailsViewHashtable = new Hashtable<Object, Object>();
	
	/** It will get stores old message for Update.*/
	public Transaction() 
	{
		td = new Transaction_details();
		tpd = new Trans_property_details();
		
		System.out.println("I'm in Transacion");
	}	
	
	
	public Transaction(DBManager sqlDB)
	{
		this.sqlDB = sqlDB;
		gin =new GetIdName(sqlDB); 
		td=new Transaction_details(sqlDB);
		tpd=new Trans_property_details(sqlDB);		
	}
		/**
	 * getInsert method inserts TransactionMap in a  Transaction table
	 * which contains all the fields presents in a given message e.g.
	 * seller,buyer,Transaction_type,Order_date,Delivery_date,
	 * amount,vat,sales_tax,service_tax,octroi,total_amount.
	 * For getInsert method of Transaction pass a table name and hashtable as a 
	 * parameter. This method is invoked by the object of DBManager i.e sqlDB. 
	 * It  create object of  Transaction_details and invokes the method 
	 * initTransaction_details of Transaction_details for the items.
	 */
	@Override
	public StringBuffer getInsert()
	{	
		boolean flagReport = false;
		boolean tplflag=false;
		if(TransactionMap.containsKey("ErrorInput"))
		{
			flagResult = false;
			return new StringBuffer(TransactionMap.toString());
		}
		//String trans_type = TransactionMap.get("transaction_type").toString();
		String id =null;
		ResultSet rs;
		if(!TransactionMap.containsKey("id"))
		{	
			try
			{
				rs = sqlDB.getSelect("select id from max_id_table where table_name = '"+masterTable+"'");
				rs.next();
				id = rs.getString("id");
			} 
			catch (Exception e)
			{
				e.printStackTrace();
			}
			TransactionMap.put("id", id); 		
		}	
		else
		{
			try {
				id=TransactionMap.get("id").toString();
				ResultSet rs1 = sqlDB.getSelect("select id from transaction where id='"+id+"'");
				if(rs1.next())
				{
					ResultSet rs2=sqlDB.getSelect("select transaction_type  from transaction where id='"+id+"'");
					if(rs2.next())
					{
						String ttype=rs2.getString("transaction_type");
						TransactionMap.put("transaction_type",gin.getItem(ttype));
					}	
					tplflag =true;
				}	
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}	
	
		
		Hashtable<Object, Object> Error = new Hashtable<Object, Object>();
		td.TransactionMap.putAll(TransactionMap);
		td.settplVector(tpd.getpropertyVector());
		Error.putAll(td.process());
		if(Error.containsKey("ErrorInput"))
		{
			return new StringBuffer(Error.toString());
		}
		else
			Error.clear();
		TransactionMap.putAll(td.TransactionMap);
		TransactionMap.put(GETPROPERTY, reqParam.getUsername());
		
		Error.putAll(process());
		TransactionMap.remove(GETPROPERTY);
		if(Error.containsKey("ErrorInput"))
		{
			return new StringBuffer(Error.toString());
		}
		TransactionMap=ConvertToLower.convertHashKey(TransactionMap);
		TransactionMap=gin.convertMasterId(TransactionMap, Request,process);
		
		// add "aja" as seller
		if(!TransactionMap.containsKey("seller"))
				TransactionMap.put("seller",gin.getId("aja"));
		try
		{
			ResultSet rs1 = sqlDB.getSelect("SELECT fieldname FROM command where msgtype = 'transaction' and process = 'add'");
			Vector<Object> columnname = new Vector<Object>();
			while(rs1.next())
			{
				String colname  = rs1.getString("fieldname").toLowerCase();
				columnname.add(colname);
			}	
			Enumeration<Object> enumtransaction = TransactionMap.keys();
			while(enumtransaction.hasMoreElements())
			{
				String col = enumtransaction.nextElement().toString();
				if(!columnname.contains(col))
				{
					Hashtable<Object, Object> propertyMap =new Hashtable<Object, Object>();					
					String newvalue = (TransactionMap.get(col).toString());
					propertyMap.put("pid",col);
					propertyMap.put("pv", newvalue);
					propertyMap = gin.ConvertPVtoVT(propertyMap);
					propertyMap = gin.convertMasterId(propertyMap, pl_tableName, process);
					tpd.TPropertyList.add(propertyMap);

					TransactionMap.remove(col);
				}
			}
		}
		catch (Exception e1) 
		{
			e1.printStackTrace();
		}
		System.out.println("o");
		
		if(!TransactionMap.containsKey("amount"))
				TransactionMap.put("amount", 0);
		
		int rs1 =0;
		if(!tplflag)
			rs1 = sqlDB.getInsert(Request, TransactionMap);
		if(rs1>0 || tplflag)
		{
			flagReport = true;
			flagResult = true;
			sbrDTB.append("Following transaction is Added..."+TransactionMap.toString());
			//tplflag = true;
			//INSERTING IN PROCESS LOGGER
		//	ProcessLogger procLogger = new ProcessLogger(sqlDB);

			//UPDATING IN PROCESS LOGGER
			
			//procLogger.updateLog(id, "0",trans_type.toString(), "5");
			
			try 
			{
				if(id == null)
				{
					id = TransactionMap.get("id").toString();
					tpd.setTid(id);
				}
				else
				{
					tpd.setTid(id);
					if(!tplflag)
						sqlDB.getUpdate("update max_id_table set id ='"+(Integer.parseInt(id)+1)+"' where table_name ='"+Request+"'");
				}
				tpd.flagResult = flagResult;
				td.setTid(id);
				//sqlDB.getUpdate("update max_id_table set id ='"+(Integer.parseInt(id)+1)+"' where table_name ='"+Request+"'");
				td.TransactionMap.putAll(TransactionMap);
				
				sbrDTB.append(tpd.getInsert());
				
				flagResult = tpd.boolTpdSetCommit;
				
				if(flagResult==true)
					sbrDTB.append(td.getInsert());
				
				flagResult = td.flagResult;
				strID = id;
			}
			catch (Exception e) 
			{
				e.printStackTrace();
			}
		}
		else
		{	
			sbrDTB.append(" pool::PropertyDetails ::getInsert():: Error..");
			flagResult = false;
			return sbrDTB;
		}
		
		try 
		{
			//Add Transsaction Details to reportMaster
			  if(flagReport == true)
			  {
				  if(reqParam.getEvent())
				  {
						try
						{
							ProcessLogger procLogger = new ProcessLogger(sqlDB);
							type=getType();
							procLogger.addLog(id, Request, process, "",reqParam.getUsername(), productName, type);
					}
					catch (Exception e) {
					}
				  }
				  
					ResultSet reportRS = sqlDB.getSelect("select PV from property_details where pid="+gin.getId("Report")+" and mid ='"+type +"' and td is null order by ref");
					while(reportRS.next())
					{
						String reportName = reportRS.getString("PV");
						//INSERTED INTO REPORT_MASTER
						sqlDB.getInsert("insert into report_master(tid, reportOn, process, report_name) values("+id+", '"+type+"', '"+"add"+"', '"+gin.getItem(reportName)+"')");
					}
			  }
		}
		catch (Exception e) 
		{
			e.printStackTrace();
		}
		//return sbrDTB.append("Inserted in TRANSACTION");
		return sbrDTB;
	}
	/**
	 * 
	 * In getUpdate of transaction seller,buyer can be 
	 * updated.
	 * @param id as a id of transaction.
	 * 
	 */
	public StringBuffer getUpdate() 
	{
	    Vector<Object> Transactionfield  =new  Vector<Object>();
	   
	    try 
	    {
	       ResultSet rs=sqlDB.getSelect("select fieldname from command where msgtype like 'transaction' and process='add'");// and isField='yes'");
		   while(rs.next())
		   { 
			   Transactionfield.add(rs.getString("fieldname"));  
		   }
	    } 
	    catch (Exception e1) 
	    {
		 e1.printStackTrace();
	    }
	    TransactionMap = ConvertToLower.convertHashKey(TransactionMap);
		ChekInMaster check = new ChekInMaster(sqlDB);
		System.out.println("In update of transaction........");
		td.reqParam =this.reqParam;
		String  id=newTransactionMap.get("id").toString();
		if(newTransactionMap.containsKey("id"))
		{
			td.setTid(newTransactionMap.get("id").toString());
			td.setTransactionMap();
			TransactionMap.putAll(td.TransactionMap);
		}
		Hashtable<Object, Object> Error = new Hashtable<Object, Object>();
		td.TransactionMap.putAll(ConvertToLower.convertHashKey(TransactionMap));
		Error.putAll(td.process());
		if(Error.containsKey("ErrorInput"))
		{
			return new StringBuffer(Error.toString());
		}
		else
			Error.clear();
		TransactionMap.putAll(td.TransactionMap);
		Error.putAll(process());
		if(Error.containsKey("ErrorInput"))
		{
			return new StringBuffer(Error.toString());
		}
		Vector<Object> newTplVector = new Vector<Object>();
        Vector<Object> oldTplVector = new Vector<Object>();
        newTransactionMap=gin.convertMasterId(newTransactionMap, Request,process);
        oldTransactionMap=gin.convertMasterId(oldTransactionMap, Request,process);
        Enumeration<Object> enume = newTransactionMap.keys();
        boolean checkflag=false;
		while(enume.hasMoreElements())
		{
			String key = enume.nextElement().toString();
			if(!Transactionfield.contains(key))
			{
				Hashtable<Object, Object> Tdplmap = new Hashtable<Object, Object>();
				String value = newTransactionMap.get(key).toString();
				value = gin.getId(value);
				if(value.equals("no$")||value.equals("0"))
				{	
					value = newTransactionMap.get(key).toString();
					Tdplmap.put("vt", value);
				}
				else
					Tdplmap.put("pv", value);
				newTransactionMap.remove(key);
				key= gin.getId(key);
				Tdplmap.put("pid", key);
				Tdplmap.put("tid", id);
				newTplVector.add(Tdplmap);				
			}	
		}
		enume = oldTransactionMap.keys();
		while(enume.hasMoreElements())
		{
			String key = enume.nextElement().toString();
			if(!Transactionfield.contains(key))
			{
				Hashtable<Object, Object> Tdplmap = new Hashtable<Object, Object>();
				String value = oldTransactionMap.get(key).toString();
				value = gin.getId(value);
				if(value.equals("no$")||value.equals("0"))
				{	
					value = oldTransactionMap.get(key).toString();
					Tdplmap.put("vt", value);
				}
				else
					Tdplmap.put("pv", value);
				oldTransactionMap.remove(key);
				key= gin.getId(key);
				Tdplmap.put("pid", key);
				Tdplmap.put("tid", id);

/*				Trans_property_details tpl = new Trans_property_details(sqlDB);
				tpl.PropertyMap.putAll(Tdplmap);			
				oldTplVector.add(Tdplmap);
*/
				oldTplVector.add(Tdplmap);

			}	
		}
		
		if (check.isInProperty_details(oldTransactionMap,masterTable) == false)
		//	Trans_property_details tpl;
		{	
			for(int j=0;j<oldTplVector.size();j++)
			{
				//tpl =  (Trans_property_details) oldTplVector.get(j);
				//Hashtable<Object, Object> tdplmap =tpl.PropertyMap;
				Hashtable<Object, Object> tdplmap =(Hashtable<Object, Object>) oldTplVector.get(j); 
				if (check.isInProperty_details(tdplmap,pl_tableName) == false)
				{
					checkflag =true;
					sbrDTB.append("Old Property Not Present ");
					System.out.println("Old Property Not Present ");
					flagResult = false;
				}
			}
			if(checkflag)
			{
				sbrDTB.append("Old Property Not Present ");
				System.out.println("Old Property Not Present ");
				flagResult = false;
				return sbrDTB;
			}
		}
		if (check.isInProperty_details(newTransactionMap,masterTable) == true)
		{
		
			for(int j=0;j<newTplVector.size();j++)
			{
			//	tpl = (Trans_property_details) newTplVector.get(j);
				//Hashtable<Object, Object> tdplmap =tpl.PropertyMap; 
					
				Hashtable<Object, Object> tdplmap =(Hashtable<Object, Object>) newTplVector.get(j); 

				if (check.isInProperty_details(tdplmap,pl_tableName) == true)
				{
					checkflag =true;

					sbrDTB.append(" Property already Not Present ");
					System.out.println("Old Property Not Present ");

					sbrDTB.append("Property Already Present ");
					System.out.println("Property Already Present ");

					flagResult = false;
				}
				else
				{
					checkflag=false;
					break;
				}
			}
			if(checkflag)
			{
				sbrDTB.append(" pool::PropertyDetails ::getUpdate():: New and Old Property are same ");
				System.out.println("pool::PropertyDetails ::getUpdate():: New and Old Property are same ");
				flagResult = false;
				return sbrDTB;
			}	
		}
		
		if((check.isInProperty_details(newTransactionMap,masterTable) == false && check.isInProperty_details(oldTransactionMap,masterTable) == true)|| checkflag==false )
		{	
			int j = sqlDB.getUpdate(Request, newTransactionMap, oldTransactionMap);
       		if(j>0 || !checkflag)
       		{
       			if(newTplVector.size()>0)
       			{	
           			Trans_property_details tpl= new Trans_property_details(sqlDB);
           			tpl.setRequestParameter(reqParam);
           			tpl.setNewPropertyVector(newTplVector);
           			tpl.setOldPropertyVector(oldTplVector);
           			tpl.getUpdate(); 
       			}      			
				sbrDTB.append("Following Transaction is updated... "+newTransactionMap.toString());
				flagResult = true;	
				strID = oldTransactionMap.get("id").toString();
							
       		}
       		else
			{
				System.out.println("pool::Transaction::getUpdate():: Unable to Update........");
				sbrDTB.append(" Unable to Update ");
				flagResult = false;
			}
       		/*Vector<Object> pdbsNewVector = new Vector<Object>();
       		Vector<Object> pdbsOldVector = new Vector<Object>();
       		oldTransactionMap.put("id",newTransactionMap.get("id"));
       		pdbsOldVector.add(oldTransactionMap); // It will create the vector for the Old property.
			pdbsNewVector.add(newTransactionMap); // It will create the vector for the New property.
			
       		setVector(pdbsNewVector, pdbsOldVector);
			getReport();*/

       	}	
		else
		{
			System.out.println("pool::MasterClass::getUpdate():: Unable to Update. old property is not present ");
			sbrDTB.append("Unable to Update. old property is not present .");
			flagResult = false;
		}
		try 
		{
			//Add Transaction Details to reportMaster
			  if(flagResult == true)
			  {
				  if(reqParam.getEvent())
				  {
						try
						{
							ProcessLogger procLogger = new ProcessLogger(sqlDB);
							type=getType();
							procLogger.addLog(id, Request, process, "",reqParam.getUsername(), productName, type);
					}
					catch (Exception e) {
					}
				  }
			
					ResultSet reportRS = sqlDB.getSelect("select PV from property_details where pid="+gin.getId("Report")+" and mid ='"+type +"' and td is null order by ref");
					while(reportRS.next())
					{
						String reportName = reportRS.getString("PV");
						//INSERTED INTO REPORT_MASTER
						sqlDB.getInsert("insert into report_master(tid, reportOn, process, report_name) values("+id+", '"+type+"', '"+"add"+"', '"+gin.getItem(reportName)+"')");
					}
			  }
		}
		catch (Exception e) 
		{
			e.printStackTrace();
		}
		return sbrDTB;
	}
	
	

	public StringBuffer getDelete()
	{
		return new StringBuffer();
	}
	public StringBuffer getView() 
	{

		StringBuffer Heading =new StringBuffer();
		StringBuffer Field=new StringBuffer();
		//MessageGenerator msg=new MessageGenerator(sqlDB);
		gin = new GetIdName(sqlDB);
		//String presentproperties="";
		//String mastermsg="";
				
		TransactionMap.putAll(ViewHashtable);
		Enumeration<Object> enumer = TransactionMap.keys();
		while(enumer.hasMoreElements())
		{
			String key=enumer.nextElement().toString();
			String value =TransactionMap.get(key).toString();
			Heading.append(key+"\t");
			Field.append(value+"\t");
		}
		//mastermsg=msg.MasterMessage(masterTable, TransactionMap, process);
		StringBuffer sbrProperty =new StringBuffer();
		
		//if(mastermsg.equals(""))
		//{
			//sbrProperty.append("Check Transaction spchar or Transaction-id ");
			//return sbrProperty;
		//}		
		
		Hashtable<Object, Object> TransactionHash = new Hashtable<Object, Object>();
		TransactionHash.putAll(TransactionMap);
		
		/*TransactionHash.putAll(ConvertToLower.convertHashKey(TransactionHash));
		Enumeration< Object> enum1 = TransactionMap.keys();
		if(enum1.hasMoreElements()==false)
		{
				sbrProperty.append("Enter condition to view the properties");
				return sbrProperty;
		}*/
		
		//According to the TransactionMap getSelectVector method checks the condition ,searches all the record
		//through databse and stores into the vrs vector.
		
		Vector<Object> vrs  = new Vector<Object>(); 
			vrs.addAll(sqlDB.getSelectVector(TransactionMap, masterTable));	
		
		//For the wrong input to the transaction request it shows null records.
		/*	
		if(vrs.isEmpty())
		{
			sbrProperty.append("Record not available");
			return sbrProperty;
		}
		*/
		for(int i=0;i<vrs.size();i++)
		{
				String presentproperty="";
				Hashtable<Object, Object> hashobj=new Hashtable<Object, Object>();
				hashobj=(Hashtable<Object, Object>) vrs.get(i);
				
				hashobj.putAll(gin.ConvertValuetoMasterName(hashobj, process, masterTable));
				hashobj.putAll(ConvertToLower.convertHashKey(hashobj));
				hashobj.remove("id");
				/*presentproperty=msg.convertToMessage(masterTable, process, hashobj);
				presentproperties=presentproperties+presentproperty;*/
				Enumeration< Object> enum1 = hashobj.keys();
				while(enum1.hasMoreElements())
				{
					String key=enum1.nextElement().toString();
					String value =hashobj.get(key).toString();
					Field.append(value+"\t");
					Heading.append(key+"\t");
				}
		}
		
		//mastermsg contains tid and presentproperties contains the whole record regarding tid.
		
		//sbrProperty.append(mastermsg+presentproperties);
				
		//call the view method of trans_property_details through the transaction request.
	
		TransactionHash.put("tid",TransactionHash.get("id"));
		TransactionHash.remove("id");		
		
		Trans_property_details Tpl;
		
		Tpl = new Trans_property_details(sqlDB);		
		Tpl.setTransactionMap(TransactionHash);
		Tpl.setViewHashtable(PropertyViewHashtable);
		Tpl.setProcess(process);
		
		sbrProperty.append(Tpl.getView());	
		try {
			String splittpl[] = sbrProperty.toString().split("\n");
			Heading.append(splittpl[0]);
			Field.append(splittpl[1]);
		} catch (Exception e) {
			e.printStackTrace();
		}
		//call the view method of transaction_details through the transaction request.
		//View method of transaction_details calls Td_property_details so the StringBuffer which returns 
		//from the view method contain item with its properties.		
		
	   /* Transaction_details td;	 
	    
	    td = new Transaction_details(sqlDB);		
		td.setTransMap(TransactionHash);
		td.setViewHashtable(TransDetailsViewHashtable);
		td.setProcess(process);
		
		sbrProperty.append(td.getView())*/;
		return Heading.append("\n"+Field);
	
	
	}
	
	
	public String getType() 
	{
		try
		{
			//if(type.length()==0)
			//	type = gin.getId(TransactionMap.get("transaction_type").toString());
			if(type.length()==0 || type=="0")
			{
				type = TransactionMap.get("transaction_type").toString();
				type = gin.getId(type);
			}
			return type;
		}
		catch (Exception e) 
		{
			e.printStackTrace();
			return "";
		}
	}

	
	public void setProcess(String tempProcess) 
	{
		process = tempProcess;
	}
	
	
	public void setPropertyVector(Vector<Object> propertydetails) 
	{
		td.PropertyList.addAll(propertydetails);	
	}

	public Hashtable<Object, Object> getBasicHashtable() 
	{
		return (TransactionMap);
	}

	
	public void setHashtable(Hashtable<Object, Object> table)
	{
		this.TransactionMap = table;
	}
	
	public void setNewProperty(Hashtable<Object, Object> NewPropertyVector)
	{
		this.newTransactionMap = NewPropertyVector;	
	}
	public void setOldProperty(Hashtable<Object, Object> OldPropertyVector)
	{
		this.oldTransactionMap = OldPropertyVector;	
	}
	
	
	
	public String getUserid(String Username)
	{
		/*String Masterpath = Input.MASTERREPORTSPATH + Username + "//" + Username + "_mid" + Input.FILRFORMAT;
		SearchRecord sr =new SearchRecord(Masterpath);*/
		
		
		Hashtable<Object, Object> table = new Hashtable<Object, Object>();
		table.put("mid",Username);
		table.put("pid", gin.getId("userid"));
		//String line[] = sr.getRecordSet(table);
		
		RecordSearch ps = new RecordSearch(sqlDB);
		ps.setConditionMap(table);
		String line[] = ps.getArrayFromResultSet();
		String userid="";
		for(int i=0;i<line.length;i++)
		{
			String splitline[]= line[i].split("\t");
			userid  = splitline[Column.pv_index-1];
		}
		return userid;
	}
	public String getTable() 
	{
		return Request;
	}
	
	public void setTransDetailsVector(Vector<Object> vector)
	{
		td.setPropertyVector(vector);
	}
	
	public void setViewHashtable(Hashtable<Object,Object> hashtable) {
		ViewHashtable.putAll(hashtable);
	}
	public void setPropertyViewHashtable(Hashtable<Object,Object> hashtable) {
		 PropertyViewHashtable.putAll(hashtable);	
	}
	
	public void setTransDetailsViewHashtable(Hashtable<Object,Object> hashtable) {
		 TransDetailsViewHashtable.putAll(hashtable);	
	}
	

	public Hashtable<Object, Object> getHashtabel() 
	{
		return (TransactionMap);
	}
	
	public Vector<Object> getpropertyVector()
	{
		return td.PropertyList;
	}

	public Hashtable<Object, Object> getDetailHashtabel() 
	{	
		try {
			Transaction_details temptd =(Transaction_details)td.PropertyList.get(td.PropertyList.size()-1);
			return (temptd.TransactionDetailMap);
		}
		catch (RuntimeException e) 
		{
		  return new Hashtable<Object, Object>();
		}
	}
	public Hashtable<Object, Object> getmasterHashtabel()
	{
		return (TransactionMap);
	}
	public void setmasterHashtabel(Hashtable<Object,Object> table)
	{
		TransactionMap = table;
	}
	

}
 